package com.example.oracle.service.serviceImpl;

import com.example.oracle.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Siaze
 * @description
 * @date 2021/11/8
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    /** 数据库服务对象 */
    @Autowired
    UserService userService;

    /** 密码加密工具 */
    @Autowired
    PasswordEncoder pe;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        com.example.oracle.pojo.User userName = new com.example.oracle.pojo.User();
        try {
            userName.setId(Long.parseLong(s));
        }catch (Exception e){
            throw new UsernameNotFoundException("账号错误");
        }

        //s为用户输入的账号用户登录会调用该方法
        List<com.example.oracle.pojo.User> user = userService.getUsers(userName);
        if(user.size() == 0){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        //设置身份
        authorities.add(new SimpleGrantedAuthority(String.valueOf(user.get(0).getRole())));
        //返回账号密码身份与用户输入的比较(只比较密码)
        return new User(String.valueOf(user.get(0).getId()), pe.encode(user.get(0).getPwd()), authorities);
    }
}
